﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using Extentions;
using Microsoft.AspNetCore.Http;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using TrainingReminderSystem.Dal;
using TrainingReminderSystem.Model;

namespace TrainingReminderSystem.Bll
{
    /// <summary>
    /// 字典表逻辑层
    /// </summary>
    public partial class SysDicBll : PcLoginedBll
    {
        #region 添加和编辑的时候 验证数据和设置默认值

        /// <summary>
        /// 添加和编辑的时候 验证数据和设置默认值
        /// </summary>
        /// <param name="db"></param>
        /// <param name="model"></param>
        /// <param name="isAdd">添加还是编辑,可以不管此参数</param>
        /// <returns>是否通过,true表示验证通过,false代表验证没有通过</returns>
        public AjaxResult<dynamic> Validate(DbEntities db, SysDic model, bool isAdd)
        {
            var r = new AjaxResult<dynamic>();
            if (model == null)
            {
                r.Message = LanguageHelper.NoSubmitData;
                return r;
            }
            if (model.EnumDicType < 0)
            {
                r.Message = "数据类型错误!";
                return r;
            }
            model.SysDicName = model.SysDicName.ExTrim();
            if (string.IsNullOrEmpty(model.SysDicName))
            {
                r.Message = "请输入类型名称!";
                return r;
            }
            model.PY = ToolHelper.GetPy(model.SysDicName);
            int storeID = CurrentStore.SysStoreID;
            if (db.SysDic.Any(m =>
                m.SysDicName == model.SysDicName && m.SysDicID != model.SysDicID && m.EnumDicType == model.EnumDicType && m.SysStoreID == storeID))
            {
                r.Message = $"您输入的{model.SysDicName}已经存在!";
                return r;
            }
            var currentEmployee = CurrentEmployee;
            if (currentEmployee != null)
            {
                model.UpdateSysEmployeeID = currentEmployee.SysEmployeeID;
            }
            model.UpdateDate = DateTime.Now;
            model.SysStoreID = storeID;
            r.Success = true;
            return r;
        }

        #endregion

        #region 分页方法

        /// <summary>
        /// 查询条件,能替换掉一些属性查询为自定义查询
        /// </summary>
        /// <param name="where"></param>
        /// <param name="key"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        private Expression<Func<SysDic, bool>> InitSearchDelegete(Expression<Func<SysDic, bool>> where,
            string key, string val)
        {
            //if (key == "SysDicID")
            //{
            //    int tempID = val.ExToInt32();
            //    return where.ExAnd(m => m.SysDicID == tempID);
            //}

            return null;
        }

        /// <summary>
        /// 分页方法
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="form"></param>
        /// <param name="sortField"></param>
        /// <param name="asc"></param>
        /// <returns></returns>
        public AjaxResult<dynamic> GetListByPage(int index, int size, IFormCollection form = null, string sortField = "", bool asc = false)
        {
            using (var db = Db)
            {
                Expression<Func<SysDic, bool>> where = InitSearch<SysDic>(form, InitSearchDelegete); //拼接查询条件方法
                if (CurrentStore != null)
                {
                    int storeID = CurrentStore.SysStoreID;
                    var storeIDList = GetAllStoreIDCache(storeID, db);
                    where = where.ExAnd(m => storeIDList.Contains(m.SysStoreID));
                }

                #region 拼接查询条件

                if (form != null)
                {
                }

                #endregion

                int counts;
                var tempIDList = db.SysDic.ExOrderBy(sortField, asc).ExGetListByPage(index, size, out counts, where).Select(m => m.SysDicID);
                var result = new AjaxResult<dynamic>() { Success = true };
                result.Total = counts;
                IQueryable<SysDic> list = db.SysDic.Where(m => tempIDList.Contains(m.SysDicID)).ExOrderBy(sortField, asc);
                result.Result = list.Select(m => new
                {
                    SysDicID = m.SysDicID,
                    EnumDicType = m.EnumDicType,
                    SysDicName = m.SysDicName,
                    PY = m.PY,
                    OrderID = m.OrderID,
                    UpdateEmployeeID = m.UpdateSysEmployeeID,
                    UpdateDate = m.UpdateDate,
                    Remark = m.Remark,
                    IsDel = m.IsDel,
                    ParentID = m.ParentID
                }).ToList();
                return result;
            }
        }

        #endregion

        #region 得到单对象,返回值有可能为null

        /// <summary>
        /// 得到单对象,返回值有可能为null
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public SysDic GetModel(int id)
        {
            using (var db = Db)
            {
                return db.SysDic.FirstOrDefault(m => m.SysDicID == id);
            }
        }

        #endregion

        #region 保存数据

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="model">保存的对象,成功之后model对象的SysDicID能得到SysDicID</param>
        /// <returns></returns>
        public AjaxResult<dynamic> Save(SysDic model)
        {
            using (var db = Db)
            {
                if (model.SysDicID <= 0)
                {
                    return this.Add(model, db);
                }
                return this.Update(model, db);
            }
        }

        #endregion

        #region 添加数据

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的SysDicID能得到SysDicID</param>
        /// <returns></returns>
        public AjaxResult<dynamic> Add(SysDic model)
        {
            using (var db = Db)
            {
                return this.Add(model, db);
            }
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的SysDicID能得到SysDicID</param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal AjaxResult<dynamic> Add(SysDic model, DbEntities db)
        {
            var r = new AjaxResult<dynamic>() { Success = false };
            if (db == null) db = Db;
            var tempAr = Validate(db, model, true);
            if (tempAr.Success == false)
            {
                r.Message = tempAr.Message;
                r.Result = tempAr.Result;
                r.Total = tempAr.Total;
                return r;
            }
            IDbContextTransaction tran = db.Database.CurrentTransaction;
            bool hasTran = tran != null;
            if (hasTran == false) tran = db.Database.BeginTransaction();
            try
            {
                db.SysDic.Add(model);
                db.SaveChanges();
                model.OrderID = model.SysDicID;
                string error = AddLog(db, model, EnumLogType.新建);
                if (!string.IsNullOrEmpty(error))
                {
                    return AjaxResult<dynamic>.ErrorResult(error);
                }
                bool isSuccess = db.SaveChanges() >= 0;
                if (hasTran == false)
                {
                    tran.Commit();
                    tran.Dispose();
                    tran = null;
                }
                r.Success = isSuccess;
                r.Message = isSuccess ? "添加成功" : "添加失败,请重试!";
                r.Result = model.SysDicID;
                return r;
            }
            catch (Exception ex)
            {
                ex.ExLogError(GetCurrentOther());
                r.Total = (int)EnumTotal.异常;
                r.Success = false;
                r.Message = "新增失败:" + ex.ExMessageWithInner();
                return r;
            }
            finally
            {
                if (hasTran == false && tran != null) tran.Rollback();
            }
        }

        #endregion

        #region 编辑

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的SysDicID能得到SysDicID</param>
        /// <returns></returns>
        public AjaxResult<dynamic> Update(SysDic model)
        {
            using (var db = Db)
            {
                return this.Update(model, db);
            }
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的SysDicID能得到SysDicID</param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal AjaxResult<dynamic> Update(SysDic model, DbEntities db)
        {
            if (CurrentEmployee != null && CurrentEmployee.IsDemo)
            {
                return AjaxResult<dynamic>.ErrorResult("试用帐号不能更改字典数据");
            }
            var r = new AjaxResult<dynamic>() { Success = false };
            if (db == null) db = Db;
            var tempAr = Validate(db, model, false);
            if (tempAr.Success == false)
            {
                r.Message = tempAr.Message;
                r.Result = tempAr.Result;
                r.Total = tempAr.Total;
                return r;
            }
            IDbContextTransaction tran = db.Database.CurrentTransaction;
            bool hasTran = tran != null;
            if (hasTran == false) tran = db.Database.BeginTransaction();
            try
            {
                var beforeModel = db.SysDic.FirstOrDefault(m => m.SysDicID == model.SysDicID);
                if (beforeModel == null)
                {
                    r.Message = LanguageHelper.NoData;
                    return r;
                }
                //beforeModel.SysDicID = model.SysDicID;
                //beforeModel.EnumDicType = model.EnumDicType;
                beforeModel.SysDicName = model.SysDicName;
                beforeModel.PY = model.PY;
                //beforeModel.OrderID = model.OrderID;
                beforeModel.UpdateSysEmployeeID = model.UpdateSysEmployeeID;
                beforeModel.UpdateDate = model.UpdateDate;
                //beforeModel.Remark = model.Remark;
                //beforeModel.IsDel = model.IsDel;
                //beforeModel.ParentID = model.ParentID;

                string error = AddLog(db, model, EnumLogType.编辑);
                if (!string.IsNullOrEmpty(error))
                {
                    return AjaxResult<dynamic>.ErrorResult(error);
                }
                var isSuccess = db.SaveChanges() >= 0;
                if (hasTran == false)
                {
                    tran.Commit();
                    tran.Dispose();
                    tran = null;
                }
                r.Success = isSuccess;
                r.Message = isSuccess ? "编辑成功" : "编辑失败,请重试!";
                r.Result = model.SysDicID;
                return r;
            }
            catch (Exception ex)
            {
                ex.ExLogError(GetCurrentOther());
                r.Total = (int)EnumTotal.异常;
                r.Success = false;
                r.Message = "编辑失败:" + ex.ExMessageWithInner();
                return r;
            }
            finally
            {
                if (hasTran == false && tran != null) tran.Rollback();
            }
        }

        #endregion

        #region 删除

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AjaxResult<dynamic> Del(int id)
        {
            using (var db = Db)
            {
                return Del(id, db);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal AjaxResult<dynamic> Del(int id, DbEntities db)
        {
            var r = new AjaxResult<dynamic>() { Success = false };
            if (db == null) db = Db;
            IDbContextTransaction tran = db.Database.CurrentTransaction;
            bool hasTran = tran != null;
            if (hasTran == false) tran = db.Database.BeginTransaction();
            try
            {
                var beforeModel = db.SysDic.FirstOrDefault(m => m.SysDicID == id);
                if (beforeModel == null)
                {
                    r.Message = LanguageHelper.NoData;
                    return r;
                }
                //db.SysDic.Remove(beforeModel);
                beforeModel.IsDel = true;

                string error = AddLog(db, beforeModel, EnumLogType.删除);
                if (!string.IsNullOrEmpty(error))
                {
                    return AjaxResult<dynamic>.ErrorResult(error);
                }
                var isSuccess = db.SaveChanges() >= 0;
                if (hasTran == false)
                {
                    tran.Commit();
                    tran.Dispose();
                    tran = null;
                }
                r.Success = isSuccess;
                r.Message = isSuccess ? "删除成功" : "删除失败,请重试!";
                return r;
            }
            catch (Exception ex)
            {
                ex.ExLogError(GetCurrentOther());
                r.Total = (int)EnumTotal.异常;
                r.Success = false;
                r.Message = "删除失败:" + ex.ExMessageWithInner();
                return r;
            }
            finally
            {
                if (hasTran == false && tran != null) tran.Rollback();
            }
        }

        #endregion
    }
}
